package com.atguigu.datastream.test.day03;

import com.atguigu.datastream.bean.Event;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * ClassName: Flink_06_Transfomat_map
 * Package: com.atguigu.test.day03
 * Description:
 *       flatmap算子
 *       如果输入的数据是Songsong，只打印用户名；如果输入的数据是Bingbing，既打印用户名又打印URL。
 * @Author ChenJun
 * @Create 2023/4/9 20:05
 * @Version 1.0
 */
public class Flink_08_Transfomat_flatmap {
    public static void main(String[] args) throws Exception {

        //1. 创建Flink 流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //2. 设置并行都
        env.setParallelism(1);

        //3 . 从端口读取数据
        DataStreamSource<String> streamSource = env.socketTextStream("localhost", 9999);

        // TODO  如果输入的数据是Songsong，只打印用户名；如果输入的数据是Bingbing，既打印用户名又打印URL。
        SingleOutputStreamOperator<String> flatMap = streamSource.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public void flatMap(String s, Collector<String> collector) throws Exception {
                //TODO 将读进来的字符串转为Event
                String[] split = s.split(",");
                Event event = new Event(split[0], split[1], Long.parseLong(split[2]));

                if ("songsong".equals(event.user)) {
                    collector.collect(event.user);
                } else if ("bingbing".equals(event.user)) {
                    collector.collect(event.user+"->"+event.url);
                }
            }
        });


        //4. 打印
        flatMap.print();

        //5. 执行
        env.execute();

    }
}
